<template>
	<view class="wy-file" >
		<slot name="body">
			<view class="wy-file-tip" v-if="showTip">
                <text class="text-sm text-grey" v-if="tip">{{tip}}</text>
				<text class="text-sm text-grey" v-else>共{{fileCount}}个附件，大小为{{fileSize}}</text> 
			</view>
			<view class="wy-file-content bg-white">
				<view class="cu-form-group" v-if="dataSet.files.length>0">
					<view class="grid col-3 grid-square flex-sub wy-margin-top-sm">
						<view v-for="(item,index) in dataSet.files" class="bg-img"  :key="index" @tap="ViewItem" :data-index="index">
							<image :src="item.cover" mode="aspectFill" style="position: absolute;height: 100%;"></image>
							<view class="cu-tag" v-if="attr.editable" @tap.stop="DelItem" :data-index="index">
								<text class="cuIcon-close text-red"></text>
							</view>
							<view v-if="attr.editable&&item.progress>0" class="cu-progress round xs striped" style="position: absolute;bottom: 0;">
								<view class="wy-bg-primary" :style="'width:'+item.progress+'%'"></view>
							</view>
						</view>
					</view>
				</view>
			</view>
			<view v-if="attr.editable && showTool" class="wy-file-tool wy-padding-lr text-center wy-padding-bottom-sm solid-bottom">
				<button @click="toEmit(tool.name)"  class="cu-tag wy-margin-top-sm wy-margin-lr-sm" v-for="(tool,index) in uploadTools" :key="index">
					<text :class="tool.icon" class="wy-text-df">{{tool.title}}</text>
				</button>

			</view>
			<!--#ifdef H5-->
				<view ref="input" style="display: none;" class="cu-tag wy-margin-top-sm wy-margin-lr-sm">

				</view>
			<!--#endif-->
		</slot>
		<view class="cu-modal"  :class="dataSet.showModal?'show':''">
			<view class="cu-dialog " style="background-color: #FFFFFF !important;">
				<view class="cu-bar bg-white justify-end">
					<view class="action"></view>
					<view class="content">录音</view>
					<view class="action" @tap="hideModal">
						<text class="cuIcon-close text-red"></text>
					</view>
				</view>
				<view class="padding-sm">
					<wy-recorder ref="cuRecorder" @RecorderEvent="RecorderEvent"></wy-recorder>
				</view>

			</view>
		</view>

		<view class="cu-modal"  :class="preview.show?'show':''">
			<view class="cu-dialog " >
				<view class="cu-bar  justify-end">
					<view class="action"></view>
					<view class="content"></view>
					<view class="action" @tap="hidePreview">
						<text class="cuIcon-close text-red"></text>
					</view>
				</view>
				<view class="padding-sm" >
					<view v-if="preview.type=='voice'">
							<audio controls name="音频文件" :src="preview.src"></audio>
					</view>
					<view v-else-if="preview.type=='video'">
						<video style="width: 600rpx;height: 400rpx;"  :src="preview.src" controls></video>
					</view>
				</view>

			</view>
		</view>
	</view>
</template>
<script>
	import {
		mapGetters,
		mapActions
	} from 'vuex';
	var wy;
	var pubfn;
	export default {
		name:'wy-file',
		data() {
			return {
				dataSet:{
					showModal:false,
					fileCount:0,
					fileSize:0,
					uploads:[
						{name:'image',title:'照片',icon:'cuIcon cuIcon-camera'},
						{name:'video',title:'视频',icon:'cuIcon cuIcon-record'},
						//#ifndef H5
						{name:'voice',title:'录音',icon:'cuIcon cuIcon-voice'},
						//#endif
						{name:'file',title:'文件',icon:'cuIcon cuIcon-file'},
					],
					files:[],
					upload:{
						active:false,
						index:0,
						files:[],
						progress:(e)=>{
							console.log(e)
						}
					}
				},
				ImgsList:{
					icon:{
						file:'',
						video:'',
						voice:''
					}
				},
				attr:{
					editable:true,
					atc:'upload',
					uploads:['image','video','voice','file']
				},
				option:{
					localCache:true
				},
				preview:{
					show:false,
					type:'',
					src:''
				}
			};
		},
		created() {
			wy = uni.wy;
			pubfn=wy.pubfn
		},
		watch:{
			fileValue(val){
				this.$emit('FileChange',val)
			}

		},
		computed:{
			uploadTools(){
				let {uploads}=this.attr
				let tools=[]
				for(let i=0;i<uploads.length;i++){
					let tool=uploads[i]
					if(tool=='image'){
						tools.push({name:'image',title:'照片',icon:'cuIcon cuIcon-camera'})
					}else if(tool=='video'){
						tools.push({name:'video',title:'视频',icon:'cuIcon cuIcon-record'})
					}
					else if(tool=='voice'){
						//#ifndef H5
						tools.push({name:'voice',title:'录音',icon:'cuIcon cuIcon-voice'})
						//#endif
					}
					else if(tool=='file'){
						tools.push({name:'file',title:'文件',icon:'cuIcon cuIcon-file'})
					}
				}
				return tools
			},
			fileValue(){
				return this.dataSet.files
			},
			fileCount(){
				return this.dataSet.files.length
			},
			fileSize(){
				let num=0
				for(let i=0;i<this.dataSet.files.length;i++){
					num+=this.dataSet.files[i].size
				}
				return this.getfileSize(num)
			}
		},
		props: {
			showTip:{
				type:Boolean,
				default:true
			},
            tip:{
                type:String,
                default:''
            },
			showTool:{
				type:Boolean,
				default:true
			},
			fileList:{
				type:Array,
				default:()=>{
					return []
				}
			},
            limitCount:{
                type:Number,
                default:20
            },
			defaultAttr:{
				type:Object,
				default:()=>{
					return {}
				}
			}
		},
		mounted() {
			if(this.fileList){
				for(let i=0;i<this.fileList.length;i++){
					this.dataSet.files.push(this.fileList[i])
				}
			}
			//#ifdef H5
			if(this.$refs.hasOwnProperty('input')){
				var input = document.createElement('input')
				let that=this
				let cover=this.ImgsList.icon.file
				input.id='btnFile'
				input.type = 'file'
				input.multiple='multiple'
				input.onchange = (event) => {
					function getObjectURL(file) {
						var url = null;
						if (window.createObjcectURL != undefined) {
						url = window.createOjcectURL(file);
						} else if (window.URL != undefined) {
						url = window.URL.createObjectURL(file);
						} else if (window.webkitURL != undefined) {
						url = window.webkitURL.createObjectURL(file);
						}
						return url;
					}
					var obj = document.getElementById("btnFile")
					let path=obj.value
					if(path){
						if(obj.files){
							for(let i=0;i<obj.files.length;i++){
								let {name,size,type}=obj.files[0]
								let res=getObjectURL(obj.files[0])
								let types=type.split('/')
								let filetype='file'
								if(types.length>1){
									filetype=types[0]
								}
								if(filetype=='video'){
									cover=that.ImgsList.icon.video
								}else if(filetype=='image'){
									cover=res
								}
								let item={
									path:res,
									cover:cover,
									size:size,
									progress:0,
									type:filetype
								}
								that.dataSet.files.push(item)
							}
						}
					}
				}
				this.$refs.input.$el.appendChild(input)
			}

			//#endif
			this.setAttr(this.defaultAttr)
			this.$emit('mounted')
		},
		methods:{
			...mapActions('file',['UploadFile']),
			hidePreview(){
				this.preview.show=false
				this.preview.src=''
				this.preview.type=''
			},
			showPreview(type,src){
                var that=this
				this.preview.type=type
                // #ifdef APP  
                let cache={ 
                	url:src,
                    type:'http',
                	pf:type
                }
                uni.showToast({
                    title:'加载中...',
                    duration:10000,
                    icon:'none'
                })
                uni.wy.pubfn.files.CacheFile(cache).then((res)=>{
                    uni.hideToast() 
                	let {path}=res  
                   // console.log(path)
                    that.preview.src=path
                    that.preview.show=true
                }).catch((err)=>{  
                    console.log(err)
                	 that.preview.src=src
                	 that.preview.show=true
                     uni.hideToast()
                })
                // #endif
                // #ifndef APP
                this.preview.src=src
                this.preview.show=true
                // #endif 
			},
			ChooseH5File(){
				var obj = document.getElementById("btnFile")
				obj.click()
				//console.log(obj)
			},
			ChooseWxFile(){
				let that=this
				wx.chooseMessageFile({
					count: 1,
					type:'all',
					success(res){
						if(res.tempFiles.length>0){
								let cover=that.ImgsList.icon.file
								for(let i=0;i<res.tempFiles.length;i++){
									let {type,path,size}=res.tempFiles[i]
									if(type=='video'){
										cover=that.ImgsList.icon.video
									}else if(type=='image'){
										cover=path
									}
									let item={
										path:path,
										cover:cover,
										size:size,
										progress:0,
										type:type
									}
									that.dataSet.files.push(item)
								}



							//that.setValue(res.tempFiles[0].path)
						}

					}
				})
			},
			setAttr(data){
				if(data){
                    let {uploads}=data
                    if(uploads){
                        this.attr.uploads=uploads
                    }
					this.attr=pubfn.deepMerge(this.attr,data)
                    
					//this.attr={...this.attr,...data}
				}

			},
			getfileSize(size){
				let num=size
				let prx='B'
				if(num>1024)
				{
					num=num/1024
					prx='K'
				}
				if(num>1024)
				{
					num=num/1024
					prx='M'
				}
				if(num>1024)
				{
					num=num/1024
					prx='G'
				}
				num=pubfn.round(num,2)
				return ''+num+prx
			},
			setOption(option){
				this.option={...this.option,...option}
			},
			fileToModel(path){
				let model={
					source:path,
					path:path
				}
				return new Promise((resolve, reject)=>{
					//#ifdef H5 || MP-WEIXIN
					model.path=path
					resolve(model)
					return
					//#endif
					if(this.option.localCache){
						wy.cacheFile({
							url:path,
							type:'local'
						}).then((res)=>{
							//console.log(res)
							model.path=res.url
							resolve(model)
						}).catch((e)=>{
							console.log(e)
							model.path=path
							resolve(model)
						})
					}else{
						resolve(model)
					}

				})
			},
            setUploadMethod(uploadEventFile){
                this.UploadFile=uploadEventFile
            },
			//回调，上传方法，，返回数据封装fid,url
			async uploadTask(callback=null,uploadMethod=null,dataMethod=null){
				let _self=this
				let {atc}=this.attr
				if(uploadMethod==null){
					uploadMethod=_self.UploadFile
				} 
				if(!this.dataSet.upload.active){
					this.dataSet.upload.active=true
					this.dataSet.upload.index=0
					this.dataSet.upload.files=[]
					for(let i=0;i<this.dataSet.files.length;i++){
						let {path,url,type,size,fid,progress}=this.dataSet.files[i]
						var ext=''
						var sps=path.split('.')
						if(sps.length>1){
							ext=sps[sps.length-1]
						}
						else{
							if(type=='video'){
								ext='mp4'
							}else if(type=='image'){
								ext='png'
							}else if(type=='voice'){
								ext='wav'
							}
						}
						let model= await this.fileToModel(path)
						//console.log(JSON.stringify(model))
						model={...model,...{url:url,size:size,type:type,progress:progress?progress:0,fid:fid?fid:0,ext}},
						this.dataSet.upload.files.push(model)
					}
				} 
				let index=this.dataSet.upload.index
				let files= this.dataSet.upload.files 
                const fileModel=index<files.length?files[index]:null
				return new Promise((resolve, reject)=>{
					if(fileModel){ 
						let {path,ext,fid}=fileModel
						if(fid){
							_self.dataSet.upload.index++
							resolve(_self.uploadTask(callback,uploadMethod,dataMethod))
						}else{ 
							uploadMethod({
								model:fileModel,
								ext,
								data:{
									filePath:path,
									atc
								},
								onUploadProgress(res){ 
                                    _self.dataSet.upload.files[index].progress=res.progress
                                    _self.dataSet.files[index].progress=res.progress
                                    if(callback!=null){
                                        callback({
                                            index:index,
                                            progress:res.progress
                                        })
                                    }
                                }
							}).then((res)=>{ 
								if(dataMethod!=null){
									res=dataMethod(res)
								}
								if(res.data){
									res=res.data
								}
								if(res.url){
									_self.dataSet.upload.files[index].url=res.url 
									if(res.fid){
										_self.dataSet.upload.files[index].fid=res.fid
									}
									_self.dataSet.upload.index++
									resolve(_self.uploadTask(callback,uploadMethod,dataMethod))
								}
								else{
									reject(res)
								}
							}).catch((e)=>{
								reject(e)
							})
						}
					}
					else{
						if(callback!=null){
							callback({
								index:index,
								progress:100
							})
						}
						this.dataSet.upload.active=false 
                        resolve(_self.dataSet.upload.files) 
					}
				})
			},
			async getFiles(){
				let files=[]
				for(let i=0;i<this.dataSet.files.length;i++){
					let {path,type,size,fid}=this.dataSet.files[i]
					let model= await this.fileToModel(path)
					//console.log(JSON.stringify(model))
					model={...this.dataSet.files[i],...model}
					files.push(model)
				}
                return new Promise((resolve, reject)=>{
                    resolve(files)
                })
				//return files
			},
			setFiles(data,attr=null){ 
				if(!attr){
					this.attr={...this.attr,...attr}
				}
				if(!pubfn.isArray(data)){
					let toData=[]
					for(let key in data){
						toData.push({
							key:key,
							...data[key]
						})
					}
					data=toData
				}
				let list=[] 
				for(let i=0;i<data.length;i++){
					let {url,path,fid,type,size}=data[i]
					if(!fid && url){
						fid=1
					}
					let cover=this.ImgsList.icon.file
					var ext=''
					if(type=='video'){
						cover=this.ImgsList.icon.video
						ext='mp4'
					}else if(type=='voice'){
						cover=this.ImgsList.icon.voice
						ext='wav'
					}else if(type=='image'){
						cover=url?url:path
						ext='png'
					}
                    path=path?path:url
					var sps=path.split('.')
					if(sps.length>1){
						ext=sps[sps.length-1]
					}
					let model={
						url:url?url:'',
						path:url?url:path,
						cover,
						size:size?size:0,
						progress:fid?100:0,
						type:type,
						fid:fid?fid:0,
						ext
					}
					list.push(model)
				}
                this.dataSet.files=list
				this.$nextTick(()=>{
					//this.dataSet.files=list 
				})
                

			},
			
            getValue(){
               // console.log(this.dataSet.files)
              var list=[]
               this.dataSet.upload.files.forEach((item)=>{
                   let {fid,url,type,ext,size}=item
                   list.push({fid,url,type,ext,size})
               })
               
                return list.length>0?list: this.fileValue
            },
            setValue(value){
              this.setFiles(value)   
            },
            async checkCommit(option,parent=null,group=''){
            	return new Promise((resolve, reject)=>{ 
                    uni.showLoading({
                        title:'上传中...'
                    })
                    this.uploadTask().then(()=>{
                        uni.hideLoading()
                        resolve({error:[],group})
                    }).catch((err)=>{
                        uni.hideLoading()
                        resolve({error:[{
                            msg: err.msg||err.errMsg,
                            param: "file",
                            parent: "" ,
                            value: ""
                        }],group})
                    })
            		
            	}) 
            },
            RecorderEvent(option){
				let {action,data}=option
				if(action=='confirm'){
					let that=this
					let {path,duration}=data
					if(path){
						let cover=this.ImgsList.icon.voice
						uni.getFileInfo({
							filePath:path,
							success(e) {
								let {size}=e
								let item={
									path:path,
									cover:cover,
									size:size,
									duration:duration,
									progress:0,
									type:'voice'
								}
								that.dataSet.files.push(item)
							},
							fail(e) {
								uni.showToast({
									title:e.errMsg,
									duration:2000
								})
							}
						})
					}
					this.hideModal()
				}
			},
			hideModal(){
				this.dataSet.showModal=false
				this.$refs.cuRecorder.clear()
			},
			showModal(){
				this.dataSet.showModal=true
				this.$refs.cuRecorder.clear()
			},
			toEmit(name){
				switch(name){
					case 'image':
						this.ChooseImage()
						break
					case 'video':
						this.ChooseVideo()
						break
					case 'voice':
						this.showModal()
						//this.$refs.cuModal.showModal()
						break
					case 'file':
						//#ifdef APP-PLUS
						this.ChooseFile()
						//#endif
						//#ifdef MP-WEIXIN
						this.ChooseWxFile()
						return
						//#endif
						//#ifndef APP-PLUS
						this.ChooseH5File()
						//#endif
						break
				}
			},
			DelItem(e){
				let {editable}=this.attr
				if(editable){
					this.dataSet.files.splice(e.currentTarget.dataset.index, 1)
				}
			},
			ViewItem(e){
				let index=parseInt(e.currentTarget.dataset.index)
				let item=this.dataSet.files[index]

				let urls=[]
				for(let i=0;i<this.dataSet.files.length;i++){
					let {path,url}=this.dataSet.files[i]
					urls.push(url?url:path)
				}
				if(item.type=='image'){
					//let urls=[item.path]
					uni.previewImage({
						urls:urls,
						current:index//item.path
					});
				}else if(item.type=='file'){
					uni.openDocument({
						filePath:item.path?item.path:item.url
					})
				}
				else{
					this.showPreview(item.type,item.path?item.path:item.url)
				}
			},
			ChooseFile(){
				let cover=this.ImgsList.icon.file
				let that=this
				pubfn.PickFile((res)=>{
					plus.io.resolveLocalFileSystemURL(res,function(fs){
						fs.file(function(file){
							let types=file.type.split('/')
							let type='file'
							if(types.length>1){
								type=types[0]
							}
							if(type=='video'){
								cover=that.ImgsList.icon.video
							}else if(type=='image'){
								cover=res
							}
							let item={
								path:res,
								cover:cover,
								size:file.size,
								progress:0,
								type:type
							}
							that.dataSet.files.push(item)
						})
					},function(e){
						uni.showToast({
							title:'该目录下文件权限不足!',
							icon:'none',
							duration:2000
						})
						console.log(e)
					})
				},'*/*')
			},
			ChooseImage() {
                var cn=this.limitCount-this.dataSet.files.length
                if(cn<=0){
                    uni.showToast({
                        title:'数量已达上限',
                        icon:'none'
                    })
                    return
                }
				uni.chooseImage({
					count:cn , //默认9
					sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
					//sourceType: ['album'], //从相册选择
					success: (res) => {
						for(let i=0;i<res.tempFiles.length;i++)
						{
							let item={
								path:res.tempFiles[i].path,
								cover:res.tempFiles[i].path,
								size:res.tempFiles[i].size,
								progress:0,
								type:'image'
							}
							this.dataSet.files.push(item)
						}
					}
				});
			},
			ChooseVideo() {
				let cover=this.ImgsList.icon.video
				uni.chooseVideo({
					success: (res) => {
						let item={
							path:res.tempFilePath,
							cover:cover,
							size:res.size,
							duration:res.duration,
							height:res.height,
							width:res.width,
							progress:0,
							type:'video'
						}
						this.dataSet.files.push(item)
					}
				});
			}
		}
	}
</script>

<style lang="scss" scoped>

</style>
